﻿using System;
using System.IO;
using System.Text;

namespace YaP.Library.Extensions
{
    internal class TextFile : IDisposable
    {
        private byte[] byteField;
        private string filepathField;
        private FileStream fs;
        private FileState streamState = FileState.Closed;
        public Encoding TextEncoding = Encoding.UTF8;

        public TextFile(string _FilePath)
        {
            if (_FilePath != string.Empty)
                FilePath = _FilePath;
            else
                new ArgumentException("Filepath cannot be null");
        }

        public byte[] Bytes
        {
            get { return byteField; }
            set { byteField = value; }
        }

        public string TextContent
        {
            get { return TextEncoding.GetString(byteField); }
            set { Bytes = TextEncoding.GetBytes(value); }
        }

        public string FilePath
        {
            get { return filepathField; }
            set { filepathField = value; }
        }

        public string[] Lines
        {
            get
            {
                string alltextfile = ReadAll(FileOperationMode.Synchronous);
                string[] toret = alltextfile.Split(System.Environment.NewLine.ToCharArray());
                return toret;
            }
        }

        public string this[int index]
        {
            get { return Lines[index]; }
        }

        public bool Open()
        {
            try
            {
                fs = new FileStream(filepathField, FileMode.OpenOrCreate);
                fs.Lock(0, fs.Length);
                streamState = FileState.Open;
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public void Close()
        {
            fs.Close();
        }

        public string ReadAll(FileOperationMode Mode)
        {
            if (streamState == FileState.Open)
            {
                if (Mode == FileOperationMode.Synchronous)
                {
                    return fs.Read(0, (int) fs.Length, Encoding.Default);
                }
                else
                {
                    return string.Empty;
                }
            }
            else
                return string.Empty;
        }

        internal void OverWrite(string p)
        {
            byte[] buff = TextEncoding.GetBytes(p);
            fs.Write(buff, 0, buff.Length);
        }

        #region IDisposable Membres

        public void Dispose()
        {
            fs.Close();
        }

        #endregion
    }
}